﻿using System;
using System.Data.Common;
using System.Runtime.Serialization;
using K3R.Data;

namespace K3R.Web.Interface {
	[DataContract]
	public class Log {
		[DataMember(Name = "id")] public LogID ID { get; set; }
		[DataMember(Name = "typeId")] public int TypeID { get; set; }
		[DataMember(Name = "typeName")] public string TypeName { get; set; }
		[DataMember(Name = "source")] public string Source { get; set; }
		[DataMember(Name = "message")] public string Message { get; set; }
		[DataMember(Name = "number")] public int Number { get; set; }
		[DataMember(Name = "timeStamp")] public DateTime TimeStamp { get; set; }

		public Log() { }

		#region Retrieval
		public static Log Load(string code, int id) {
			using (var conn = new Connection(Settings.Profiles[code].ConnectionString, "k3r_sqlLogging_loadLog")) {
				conn.AddParameter("@id", id);

				var dr = conn.ExecuteReader();
				if (dr.Read())
					return Convert(code, dr);
				else throw new Exception("Not Found");
			}
		}

		public static Log Load(LogID id) {
			return Load(id.Code, id.ID);
		}

		public static Log Load(int id) {
			var profile = Settings.Profiles[0];
			using (var conn = new Connection(profile.ConnectionString, "k3r_sqlLogging_loadLog")) {
				conn.AddParameter("@id", id);

				var dr = conn.ExecuteReader();
				if (dr.Read())
					return Convert(profile.Code, dr);
				else throw new Exception("Not Found");
			}
		}
		#endregion

		#region Conversion
		internal static Log Convert(string code, DbDataReader dr) {
			return new Log {
				ID = new LogID {
					ID = (int)dr["id"],
					Code = code
				},
				TypeID = (int)dr["type"],
				TypeName = dr["typeName"].ToString(),
				Source = dr["source"].ToString(),
				Message = dr["message"].ToString(),
				Number = dr["number"].DBValueOrDefault<int>(),
				TimeStamp = (DateTime)dr["ts"]
			};
		}
		#endregion
	}
}
